const Service = require("egg").Service;

class DeviceService extends Service {


    //设备列表
    async index(payload) {

        const { page=1, pageSize=10 } = payload

        const limit = parseInt( pageSize )

        const offset = (page - 1) * limit

        const lists = await this.ctx.model.TPrideviceinfo.findAndCountAll({
            limit,
            offset,
            include: [
                {
                    model: this.app.model.TDevicetype,
                    as: 'devicetype',
                    attributes: ['dt_typeid', 'dt_typememo'],
                },
            ]
        })

        return lists
    }

    //通过原生查询获取设备数据
    async getSourceData(payload) {

        const { page=1, pageSize=10 } = payload

        const limit = parseInt( pageSize )

        const offset = (page - 1) * limit

        const { app } = this

        const sql = `
            select a.pdi_index, a.pdi_name, a.pdi_code, a.dpt_id, a.SubType, a.pdi_updatetime, b.dt_typememo, c.ts_TypeMo from t_prideviceinfo a 
            left join t_devicetype b on a.dpt_id = b.dt_typeid
            left join t_subdevicetype c on a.dpt_id = c.ts_Maintypeid and a.SubType = c.ts_typeid
            order by pdi_updatetime desc 
            limit :offset, :limit
        `

        const lists = await app.model.query(sql, { 
            type: app.Sequelize.QueryTypes.SELECT,
            raw: true,
            replacements: { 
                limit,
                offset
            }, 
        })

        const countSql = `
            select count(1) as total from t_prideviceinfo a 
            left join t_devicetype b on a.dpt_id = b.dt_typeid
            left join t_subdevicetype c on a.dpt_id = c.ts_Maintypeid and a.SubType = c.ts_typeid
        `
        const count = await app.model.query(countSql, { 
            type: app.Sequelize.QueryTypes.SELECT,
            raw: true,
        })

        const [ { total } = { total: 0} ] = count


        return { rows: lists, count: total }
    }    

    //显示设备详细信息
    async show(id) {

        const device = await  this.ctx.model.TPrideviceinfo.findByPk(id)

        return device;
    }

    //添加设备
    async add(payload) {

        const device = await  this.ctx.model.TPrideviceinfo.create(payload)

        return device;
    }

    //更新设备列表
    async update(id, payload) {

        const device = await  this.ctx.model.TPrideviceinfo.findByPk(id)

        if (!device) {
            this.ctx.throw(422, this.ctx.__("The data does not exist"));
        }

        await device.update(payload);

        return device;
    }

    //删除设备
    async destroy(id) {

        const device = await  this.ctx.model.TPrideviceinfo.findByPk(id)

        if (!device) {
            this.ctx.throw(422, this.ctx.__("The data does not exist"));
        }

        return await device.destroy();
    }


}

module.exports = DeviceService